#!/usr/bin/env python
#
# The MIT License
#
# Copyright (c) 2008 Nicholas Galbreath
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#

from boto.ec2.connection import EC2Connection
def ec2ip_list():	 
    conn = EC2Connection()
    addresses = conn.get_all_addresses()
    for adr in addresses:
	    print "%s -> %s" % (adr.public_ip, adr.instance_id)


def ec2ip_get():
	conn= EC2Connection()
	adr = conn.allocate_address()
	print adr

def ec2ip_release(ip):
	conn= EC2Connection()
	status = conn.release_address(ip)
	print status

def ec2ip_disassociate(ip):
	conn= EC2Connection()
	status = conn.disassociate_address(ip)
	print status

def ec2ip_associate(ip, instance):
	conn= EC2Connection()
	status = conn.associate_address(instance, ip)
	print status

if __name__ == '__main__':
    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option('-l', '--list', dest='list',
		      action='store_true', default=False,
		      help='List public IPs')

    parser.add_option('-g', '--get', dest='get',
		      action='store_true', default=False,
		      help='Get a new IP address')

    parser.add_option('-r', '--release', dest='release',
		      default=None,
		      help='Release an IP address')

    parser.add_option('-d', '--disassociate', dest='disassociate',
		      default=None,
		      help='Disassociate a public ip address from any instance')
    parser.add_option('-a', '--associate', dest='associate',
		      default=None,
		      help='Aassociate a public ip address to an  instance')


    options, args = parser.parse_args()

    if options.list:
	    ec2ip_list()
    elif options.get:
	    ec2ip_get()
    elif options.release:
	    ec2ip_release(options.release)
    elif options.disassociate:
	    ec2ip_disassociate(options.disassociate)
    elif options.associate:
	    ec2ip_associate(options.associate, args[0])

